<template>
  <div>
    <ylheader :leftsvg="true" :rightsvg="false" :title="'详情'"  @moresvg="deletemycomment" :rightcollectsvg="rightcollectsvgicon" @collectevent="iscollectevent"></ylheader>
    <deletepopup :type="myshenhetype" @candelete="deletetopiccomments" @cancledelete="canaledeteletopiccomments" :isshowdeletepopup="showdelete"  @deleteshow="deleteshow"></deletepopup>
    <mt-popup
      v-model="isdelete" position="bottom">
      <div style="width: 7.5rem;display: flex;flex-direction: column;align-items: center">
        <div class="delete" @click="deletemycomments">
          <span>删除</span>
        </div>
        <div style="background-color: #f5f5f5;height: 0.1rem;width: 100%"></div>
        <div @click="iscancle" class="cancle" >
          <span>取消</span>
        </div>
      </div>
    </mt-popup>

    <mt-popup
      v-model="isreply" position="bottom">
      <div style="width: 7.5rem;display: flex;flex-direction: column;align-items: center">
        <div class="delete" @click="replycom">
          <span>回复</span>
        </div>
        <div style="background-color: #f5f5f5;height: 1px;width: 100%"></div>
        <div v-if="ismyself==true" class="delete" @click="deletereply">
          <span>删除</span>
        </div>
        <div style="background-color: #f5f5f5;height: 0.1rem;width: 100%"></div>
        <div class="cancle" @click="replycancle">
          <span>取消</span>
        </div>
      </div>
    </mt-popup>
    <div class="loadmore-container" ref="myWrapper">
      <div class="loadmore-ul">
        <div v-model="discuss" style="background-color: white;" >
          <div style="width:100%;padding: .3rem;">
            <img :src="discuss.headImg" style="width:40px;height:40px;border-radius: 50%;float: left;margin-right: .3rem">
            <span style="display: inline-block;float: left;height:40px;line-height: 40px;">{{discuss.nickName}}</span>
            <!-- <span  style="display: inline-block;float: right;height:40px;line-height: 40px;color:#999">{{showtime(discuss.gmtModified)}}</span>
           -->
           <span  style="display: inline-block;float: right;height:40px;line-height: 40px;color:#999">{{discuss.gmtModified}}</span>
           </div>
          <div style="clear: both"></div>
          <div style="width:100%;margin-top: 5px;padding: .3rem;">
            <p style="word-wrap: break-word;"><router-link :to="{name:'discoveryDetails',query:{id:discuss.circleId}}">#{{discuss.name}}#</router-link>{{discuss.content}}</p>
            <img  v-for="(img,i) in changeDisPics(discuss.pics)" :src="img" v-if="discuss.pics" @click="popupImg(changeDisPics(discuss.pics),i)"
                  style="width:2.1rem;height:1.7rem;margin-right: .15rem;margin-top: .1rem; border-radius: 3px;">
            <!-- <mt-popup
              v-model="popupVisible"
              popup-transition="popup-fade"
              :modal="true"
            >
              <img :src="popImg" style="width:100%;">
            </mt-popup> -->
          </div>
          <!--<hotheader  :type="1" :nickname="discuss.name" :saytime="discuss.gmtModified" :avatarimg="discuss.pic"
                     :place="discuss.parks"  :userType="discuss.userType" :isTalent="discuss.isTalent" :pendantType="discuss.pendantType" :pendantPicUrl="discuss.pendantPicUrl"></hotheader>
          <commentbody :commenttype="null" :commenttext="discuss.introduction"
                       :piclength="changeStrtoArr(discuss.pic).length" :picarray="changeStrtoArr(discuss.pic)"></commentbody>-->
        </div>
        <div style="margin-top: 0.2rem">
          <div class="allcomments">
            <div>全部评论<span style="margin-left: 0.2rem">(<span style="color: #fb6856;">{{commentcounts}}</span>)</span></div>
          </div>
          <div style="background-color: white;padding-bottom: 0.95rem;min-height:80vh;">
            <div class="comment" v-for="(items,index) in commentList" :key="index">
              <commentdetailheader :zannum="items.likeNum" :avaterImg="items.headImg" :name="items.nickName" :time="items.timeStamp" :commentindex="index"
                                   :commentdetailisup="items.isLike" @comentdetailthumb="iscomentdetailthumb(items,index)" @replycomment="replyother" :userType="items.userType" :isTalent="items.isTalent" :pendantType="items.pendantType" :pendantPicUrl="items.pendantPicUrl"></commentdetailheader>

              <commentbody @showImg="popupImg"  :atname="items.atName" :commenttype="items.atName" :commenttext=changeContent(items)
                            :piclength="changeStrtoArr(items.pics).length"   :picarray="changeStrtoArr(items.pics)" @replycomment="replyother" :commentindex="index"></commentbody>

            </div>
          </div>
        </div>
      </div></div>
    <div v-model="discuss" style="background-color: white;" >
      <div style="position: fixed;bottom: 0;width: 100%;z-index: 2;height: 0.9rem;">
        <div class="bottom-sep"></div>
        <thumb-up :topiccommentnum="commentcounts" :thumbupnum="discuss.likeNum" :commentindex="1" :isup="discuss.isLike"
                  @thumbup="saythumbup" @commentsvgg="saycomment"></thumb-up>

      </div>
    </div>
    <transition name="fade">
     <div class="modal-img" v-if="popupVisible" @click="popupVisible=false">
       <mt-swipe :auto="100000" style="width: 100%;height: 100vh;position:relative;"
       :continuous="false" 
        :defaultIndex="swiperIndex" :showIndicators="false" >
          <mt-swipe-item v-for="(item,index) in popImg" :key="index" style="height:100vh" >
            <img v-lazy="item" class="swiper-img" />
          </mt-swipe-item>
        </mt-swipe>
      </div>
    </transition>
  </div>
</template>
<script>
import ylheader from "src/components/yl-header.vue";
import hotheader from "src/components/allhot-header.vue";
import commentbody from "src/components/comment-detail-body.vue";
import commentdetailheader from "src/components/commentdetail-header.vue";
import thumbUp from "src/components/thumb-up.vue";
import { Pupup } from "mint-ui";
import api from "src/api/index";
import deletepopup from "src/components/deletepopup.vue";
export default {
  name:"disdetail",
  data() {
    return {
      isuptype: 0,
      isdelete: false,
      isreply: false,
      headertype: this.$route.query.type,
      commentList: [],
      discuss: {},
      commentcounts: "",
      tag: "",
      ismyself: "",
      isme: "",
      showdelete: false,
      mystatus: "",
      popupVisible:false,
      popImg:'',
      page: 1,
      myshenhetype: -1,
      is_r: false,
      hasmore: false,
      rightcollectsvgicon:0,//0未收藏，1已收藏
    };
  },
  created() {
    const addclick = {
      id: this.$route.query.circleId,
      type: 2
    };
    this.$util.saveclicknum(addclick);
    this.initSay()
    this.initdiscomments()
  },
  components: {
    ylheader,
    hotheader,
    commentbody,
    commentdetailheader,
    thumbUp,
    Pupup,
    deletepopup,
  },
  methods: {
    showtime(time) {
      let date =
        typeof time === "number"
          ? new Date(time)
          : new Date((time || "").replace(/-/g, "/"));
      let diff = (new Date().getTime() - date.getTime()) / 1000;
      let dayDiff = Math.floor(diff / 86400);
      let isValidDate =
        Object.prototype.toString.call(date) === "[object Date]" &&
        !isNaN(date.getTime());

      if (!isValidDate) {
        window.console.error("不是有效日期格式");
      }
      const formatDate = function(date) {
        let today = new Date(date);
        let year = today.getFullYear();
        let month = ("0" + (today.getMonth() + 1)).slice(-2);
        let day = ("0" + today.getDate()).slice(-2);
        let hour = today.getHours();
        let minute = today.getMinutes();
        let second = today.getSeconds();
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      };

      if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
        return formatDate(date);
      }
      return (
        (dayDiff === 0 &&
          ((diff < 60 && "刚刚") ||
            (diff < 120 && "1分钟前") ||
            (diff < 3600 && Math.floor(diff / 60) + "分钟前") ||
            (diff < 7200 && "1小时前") ||
            (diff < 86400 && Math.floor(diff / 3600) + "小时前"))) ||
        (dayDiff === 1 && "昨天") ||
        (dayDiff < 7 && dayDiff + "天前") ||
        (dayDiff < 31 && Math.ceil(dayDiff / 7) + "周前")
      );
    },
       //显示图片
    popupImg(data,index){
      this.swiperIndex = index
      if(typeof data == 'string'){
        data = data.split(',')
      }
       //console.log(data,index)
      this.popImg = data;
      this.popupVisible = true;
      // console.log(this.swiperOne)
      // this.swiperOne.slideTo(index)
    },
    // popupImg(imgarray){
    //   // this.popupVisible = true;
    //   // this.popImg=img;
    //   let imgstr = [];
    //   _each(imgarray,(v,i)=>{
    //     imgstr.push(v.src);
    //   })
    //   console.log(imgarray)
    //   window.location.href= "image://?url=" + imgstr + "&currentIndex=" + 0;

    // },
    changeDisPics(item){
      return item?item.split(','):[];
    },
    changeContent(item){
      let content = ''
      if(item.beCircleDiscussCommentUserId>0){
        content = `<span style="color:dodgerblue">回复</span>：<i style="color:red">@${item.beNickName}</i> ${item.content}`
      }else{
        content = item.content;
      }
      return content;
    },
    changeStrtoArr(str){
      if(!str) return false;
      let strArr = str.split(',');
      let newArr = [];
      for(let i=0; i<strArr.length;i++){
        newArr.push({'src':strArr[i]})
      }
      return newArr
    },
    initSay() {
      const data = {
        id: this.$route.query.circleId,
      };
      api.queryDiscoveryInfo(data).then(res => {
        if (res.success) {
          this.discuss = JSON.parse(localStorage.getItem('infofo'));
          this.discuss.isLike = localStorage.getItem('isLike');

        } else {
          // resolve("获取详情失败...");
        }
      });
    },
    initdiscomments() {
      if (this.hasmore) this.page += 1;
      const params = {
        page: this.page,
        limit: 30,
        circleId: this.$route.query.circleId,
        circleDiscussId: this.$route.query.circleDiscussId,
      };
      api.Querycirclediscusscommentlist(params).then(res => {
        if (res.success) {
          /*if(!res.page||res.page.list.length==0){
            this.commentcounts=0;
              return;
            }*/
          this.commentList = [...this.commentList, ...res.page.list];
          this.$util.getListUrl(this.commentList);
          // var tempLength = this.commentList.length;
          /* if (tempLength != 0) {
             this.picAutoOrient(res.data.currPage-1,this.commentList);
           }*/
          this.commentcounts = res.page.totalCount;
          if (res.page.currPage < res.page.totalPage) {
            this.is_r = false;
            this.hasmore = true;
          } else {
            this.hasmore = false;
          }
          if (this.page > 1) {
            setTimeout(() => {
              this.myscroll.refresh();
            }, 0);
          }
          // resolve("获取详情...");
        } else {
          // resolve("获取详情失败...");
        }
      });
    },
    //初始化scroll
    initScroll() {
      let p = new Promise((resolve, reject) => {
        let myWrapper = this.$refs.myWrapper;
        let _this = this;
        this.$nextTick(() => {
          localStorage.tempPageHeight = document.getElementsByClassName(
            "loadmore-ul"
          )[0].scrollHeight;
          _this.myscroll = new iScroll(myWrapper, {
            onScrollMove: function() {
              if (
                this.y <= this.wrapperH - this.scroller.clientHeight - 50 &&
                _this.hasmore &&
                _this.is_r == false
              ) {
                _this.is_r = true;
                _this.initdiscomments();
              }
            },
            onScrollEnd: function() {},
            onScrollStart: function() {
              if (
                localStorage.tempPageHeight !=
                document.getElementsByClassName("loadmore-ul")[0].scrollHeight
              ) {
                this.refresh();
                localStorage.tempPageHeight = document.getElementsByClassName(
                  "loadmore-ul"
                )[0].scrollHeight;
              }
            }
          });
          resolve("初始化scroll");
        });
      });
      return p;
    },
    deletetopiccomments() {
      this.showdelete = false;
      if (this.mystatus == "big") {
        const data = {
          circleId: this.$route.query.circleId
        };
        api.Querydeletesays(data).then(res => {
          if (res.success) {
            this.discuss.pop();
            this.isdelete = false;
            localStorage.turnCount = "";
            this.$router.go(-1);
            //              this.commentList = []
          } else {
            this.$toast("删除失败");
          }
        });
      } else if (this.mystatus == "small") {
        if (
          localStorage.getItem("userId") != this.commentList[this.tag].userId
        ) {
          return;
        }
        const id = {
          commentId: this.commentList[this.tag].commentId
        };
        api.Querydeletesayscomments(id).then(res => {
          if (res.success) {
            this.isreply = false;
            this.commentList.splice(this.tag, 1);
            this.commentcounts -= 1;
          } else {
            this.$toast("删除失败");
          }
        });
      }
    },
    saythumbup(data) {
      const params = {
        circleId: this.$route.query.circleId,
        circleDiscussId: this.$route.query.circleDiscussId
      };
      this.commentList = [];
      if (this.discuss.isLike == 0) {
        api.queryDiscoverylikeadd(params).then(res => {
          if (res.success) {
            this.initdiscomments();
            // this.$util.saveFootPrint({actType:9,typeValue:this.$route.query.circleId});//用户轨迹
            this.discuss.isLike = 1;
            this.discuss.likeNum += 1;
            let sayObj = JSON.parse(localStorage.sayStorage);
            sayObj.commentlist.isLike = 1;
            sayObj.commentlist.likes = this.discuss.likeNum;
            let tempSayObj = JSON.stringify({
              commentlist: sayObj.commentlist,
              totalPage: sayObj.totalPage,
              hasmore: sayObj.hasmore,
              pageone: sayObj.pageone,
              pagetwo: sayObj.pagetwo,
              mypage: sayObj.mypage,
              timeorhot: sayObj.timeorhot
            });
            localStorage.sayStorage = tempSayObj;
          }
        });
      } else if (this.discuss.isLike == 1) {
        api.queryDiscoverylikecancel(params).then(res => {
          if (res.success) {
            this.initdiscomments();
            this.discuss.isLike = 0;
            this.discuss.likeNum -= 1;
            let sayObj = JSON.parse(localStorage.sayStorage);
            // sayObj.commentlist[this.$route.query.index].likeNum = this.discuss.likeNum;
            // sayObj.commentlist[this.$route.query.index].isLike = 0;
            sayObj.commentlist.likeNum = this.discuss.likeNum;
            sayObj.commentlist.isLike = 0;
            let tempSayObj = JSON.stringify({
              commentlist: sayObj.commentlist,
              totalPage: sayObj.totalPage,
              hasmore: sayObj.hasmore,
              pageone: sayObj.pageone,
              pagetwo: sayObj.pagetwo,
              mypage: sayObj.mypage,
              timeorhot: sayObj.timeorhot
            });
            localStorage.sayStorage = tempSayObj;
          }
        });
      }
    },
    saycomment(data) {
      this.$router.push({
        path: "/publishdis",
        query: {
          circleId: this.$route.query.circleId,
          userId: this.$route.query.userId,
          circleDiscussId: this.$route.query.circleDiscussId,
          commentid: this.$route.query.commentid,
          index: this.$route.query.index
        }
      });
    },

    iscomentdetailthumb(data,index) {
      console.log(data)
      const likeparam = {
        circleDiscussCommentId: data.id,
        circleDiscussId: data.circleDiscussId,
        circleId: data.circleId,

      };
      const canclelikeparam = {
        circleDiscussCommentId: data.circleDiscussCommentId
      };
      if (data.isLike == 0) {
        api.Querycirclediscusscommentthumbup(likeparam).then(res => {
          if (res.success) {
            // this.$util.saveFootPrint({actType:10,typeValue:this.commentList[data.commentindex].commentId});//用户轨迹
            this.commentList[index].isLike = 1;
            this.commentList[index].likeNum = data.likeNum?1+data.likeNum:1;
            // this.commentList=[]
            // this.initdiscomments()

          } else {
            this.$toast("点赞失败");
          }
        });
      } else if (data.isLike == 1) {
        api.Querycanclecirclediscusscommentlikethumbup(likeparam).then(res => {
          if (res.success) {
            this.commentList[index].isLike = 0;
            this.commentList[index].likeNum = data.likeNum?data.likeNum-1:1;
            // this.commentList=[]
            // this.initdiscomments()

          } else {
            this.$toast("取消点赞失败");
          }
        });
      }
    },
    deletemycomment() {
      const data = {
        type: "2",
        id: this.$route.query.circleId
      };
      api.Queryshenhe(data).then(res => {
        if (res.success) {
          if (res.data == "1") {
            this.myshenhetype = 2;
          } else if (res.data == "0") {
            this.myshenhetype = 1;
          }
        }
      });
      this.isdelete = true;
    },
    deletemycomments() {
      this.isdelete = false;
      this.showdelete = true;
      this.mystatus = "big";
    },
    canaledeteletopiccomments() {
      this.showdelete = false;
    },
    iscancle() {
      this.isdelete = false;
    },
    replyother(data) {
      if (
        localStorage.getItem("userId") ==
        this.commentList[data.commentindex].userId
      ) {
        this.ismyself = true;
      } else {
        this.ismyself = false;
      }
      this.isreply = true;
      this.tag = data.commentindex;
      if(this.ismyself){
        const mydata = {
          type: "3",
          id: this.commentList[data.commentindex].commentId
        };
        api.Queryshenhe(mydata).then(res => {
          if (res.success) {
            if (res.data == "1") {
              this.myshenhetype = 2;
            } else if (res.data == "0") {
              this.myshenhetype = 1;
            }
          }
        });
      }
    },

    replycom() {
      this.$router.push({
        path: "/publishdis",
        query: {
          circleId: this.$route.query.circleId,
          userId: this.$route.query.userId,
          beCircleDiscussCommentUserId: this.commentList[this.tag].userId,
          circleDiscussId: this.$route.query.circleDiscussId,
          commentid: this.$route.query.commentid,
          index: this.$route.query.index,
          beCircleDiscussCommentId: this.commentList[this.tag].id
        }
      });
    },
    deletereply() {
      this.isreply = false;
      this.showdelete = true;
      this.mystatus = "small";
    },
    replycancle() {
      this.isreply = false;
    },
    //图片自动旋转参数
    picAutoOrient(page,data) {
      for (var m = 10*page; m < data.length; m++) {
        if (data[m].picture.length != 0) {
          for (var n = 0; n < data[m].picture.length; n++) {
            data[m].picture[n].src =
              data[m].picture[n].src + "?imageMogr2/auto-orient";
          }
        }
      }
    },
    iscollectevent(data){
      if(this.rightcollectsvgicon==0){
        const params = {type:1,itemId:this.$route.query.circleId};
        api.addCollection(params).then(res=>{
          if(res.success){
            this.$util.saveFootPrint({actType:14,typeValue:this.$route.query.circleId});//用户轨迹
            this.rightcollectsvgicon=1;
            this.$toast("收藏成功");
          }
        })
      }else if(this.rightcollectsvgicon==1){
        const params = {type:1,itemId:this.$route.query.circleId};
        api.cancelCollection(params).then(res=>{
          if(res.success){
            this.rightcollectsvgicon=0;
            this.$toast("取消收藏成功");
          }
        })
      }
    },
    deleteshow(data){
      this.showdelete=data;
    },
  }
};
</script>
<style lang="less" scoped>
.modal-img{
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,.5);
  position: fixed;
  top:0;
  left: 0;
  z-index: 9999;
  img{
    width: 80%;
    position: absolute;
    top:50%;
    left: 10%;
    transform: translateY(-50%);
  }
}
.allcomments {
  width: 100%;
  height: 0.89rem;
  background-color: white;
  line-height: 0.88rem;
  font-family: "PingFangSC Regular";
  font-size: 0.3rem;
  color: #666666;
  div {
    margin-left: 0.3rem;
    width: 6.9rem;
    height: 0.88;
    border-bottom: 1px solid #e6e6e6;
  }
}
.bottom-sep {
  width: 6.9rem;
  margin-left: 0.3rem;
  height: 1px;
  background-color: #e6e6e6;
}
.delete {
  height: 0.9rem;
  line-height: 0.9rem;
  font-size: 0.3rem;
  color: #333333;
  font-family: "PingFangSC Regular";
  width: 100%;
  text-align: center;
}
.cancle {
  height: 0.9rem;
  width: 100%;
  text-align: center;
  line-height: 0.9rem;
  font-size: 0.3rem;
  color: #de4b4e;
  font-family: "PingFangSC Regular";
}
.loadmore-container {
  overflow: auto !important;
  height:100% !important;
  margin: 0 auto;
}
.loadmore-ul {
  padding-bottom: 1.2rem;
  list-style: none;
}
.img-box {
  margin-left: -0.15rem;
}
.img-box img{
  width: 2.2rem;
  height: 1.7rem;
  float: left;
  margin-left: .15rem;
  margin-top: .1rem;
  border-radius: 3px
}
</style>
